package service

import (
	"context"
	"mall/api/mall"
	"mall/internal/model"
	"mall/pkg/util"
)

func (s *Service) StatsGetMemberOrders(ctx context.Context, req *mall.StatsGetMemberOrdersRequest) (
	resp *mall.StatsGetMemberOrdersResp, err error) {
	if err = s.downstream.CheckMemberPermission(ctx, req.Token, req.PStoreId); err != nil {
		return
	}
	var (
		orders    []*model.MemberOrderWebQuery
		memberIds []int64
	)
	if memberIds, err = s.downstream.QueryMemberIDs(ctx, req.MemberId, req.Token.SgId); err != nil {
		return
	}
	resp = &mall.StatsGetMemberOrdersResp{Orders: make([]*mall.MemberOrderStatsView, 0)}
	if orders, resp.Total, err = s.dao.FindMemberStatsOrdersByPage(
		ctx, req.Token.SgId, req.PStoreId, req.PageNo, req.PageSize, memberIds); err != nil {
		return
	}
	for _, order := range orders {
		resp.Orders = append(resp.Orders, &mall.MemberOrderStatsView{
			SubmitTime:     order.SubmitTime.Format(util.DefaultLayout),
			OrderNumber:    order.OrderNumber,
			Amount:         order.Trans,
			RefundedAmount: order.Refunded,
		})
	}
	return
}
